package evi.com.evi.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import evi.com.evi.R;
import evi.com.evi.adapter.GoodsSortAdapter;
import evi.com.evi.application.MyApplication;
import evi.com.evi.bean.ClassifyBean;
import evi.com.evi.bean.GoodsManagerBean;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.SPUtil;
import evi.com.evi.utils.ScreenUtils;
import evi.com.evi.utils.ToastUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static org.bouncycastle.crypto.tls.ConnectionEnd.client;


/**
 * 编辑分类列表
 *
 * @author MY
 */
public class GoodsSortWriteActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "TAG";

    private ImageView tv_return_back; // 返回
    private LinearLayout ll_add;

    private ListView lv_goods_sort;
    private GoodsSortAdapter mGoodsSortAdapter;
    private List<ClassifyBean> sortList; //分类List
    private List<String> sizeList; //分类对应的商品数量

    private OkHttpClient client;
    private JSONUtils jsonUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenUtils.setTranStatus(this, false, Color.parseColor("#FF6600"));
        MyApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_goods_sort_write);
        initView();

        client = new OkHttpClient();
        jsonUtils = new JSONUtils();

        sortList = new ArrayList<>();
        sizeList = new ArrayList<>();
        getGoodsInfo();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_return_back: // 返回
                setResult(RESULT_OK);
                this.finish();
                break;
            case R.id.ll_add: // 添加分类
                Intent intent2 = new Intent(GoodsSortWriteActivity.this, GoodsUpdateActivity.class);
                intent2.putExtra("ActType", "添加分类");
                startActivityForResult(intent2, 1);
                break;
            default:
                break;
        }
    }

    private void initView() {
        tv_return_back = (ImageView) findViewById(R.id.tv_return_back);
        tv_return_back.setOnClickListener(this);

        ll_add = (LinearLayout) findViewById(R.id.ll_add);
        ll_add.setOnClickListener(this);

        lv_goods_sort = (ListView) findViewById(R.id.lv_goods_sort);
    }

    //返回回调方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                sortList.clear();
                getGoodsInfo();
            }
        }
    }

    private void showInfo() {
        Comparator<ClassifyBean> comparator = new Comparator<ClassifyBean>() {
            @Override
            public int compare(ClassifyBean o1, ClassifyBean o2) {
                return o1.getSort().compareTo(o2.getSort());
            }
        };
        Collections.sort(sortList, comparator);
        mGoodsSortAdapter = new GoodsSortAdapter(GoodsSortWriteActivity.this, sortList, sizeList);
        lv_goods_sort.setAdapter(mGoodsSortAdapter);
    }


    /**
     * 删除分类
     * deleteCategoryId    被删除的分类ID
     * newCategoryId       商品移到的分类ID
     */
    public void deleteSort(String deleteCategoryId, String newCategoryId) {
        String token = SPUtil.getString(this, "token");

        FormBody.Builder builder = new FormBody.Builder();

        RequestBody body = null;
        if (newCategoryId == null) {
            body = builder
                    .add("deleteCategoryId", deleteCategoryId)
                    .build();
        } else {
            body = builder
                    .add("deleteCategoryId", deleteCategoryId)
                    .add("newCategoryId", newCategoryId)
                    .build();
        }

        Request request = new Request.Builder()
                .addHeader("token", token)
                .post(body)
                .url(ContentUtils.deleteProductCategory_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showMsg(GoodsSortWriteActivity.this, "删除分类成功");
                                getGoodsInfo();
                            }
                        });
                    } else {
                        toast("删除分类失败");
                    }
                }
                Log.e(TAG, "添加商品分类联网成功" + jsonData);
            }
        });

    }

    /**
     * 移动分类
     * categoryIdA    分类ID1
     * categoryIdA    分类ID2
     */
    public void moveSort(String categoryIdA, String categoryIdB) {
        String token = SPUtil.getString(this, "token");

        FormBody.Builder builder = new FormBody.Builder();

        RequestBody body = builder
                .add("categoryIdA", categoryIdA)
                .add("categoryIdB", categoryIdB)
                .build();

        Request request = new Request.Builder()
                .addHeader("token", token)
                .post(body)
                .url(ContentUtils.swapProductCategorySort_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                getGoodsInfo();
                            }
                        });
                    } else {
                        toast("移动分类失败");
                    }
                }
                Log.e(TAG, "移动商品分类联网成功" + jsonData);
            }
        });

    }


    /**
     * 查询所有分类
     */
    private void getGoodsInfo() {
        String token = SPUtil.getString(this, "token");
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.merchantCategoryProducts_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器忙碌，请稍后再试");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("categories");
                        sortList.clear();
                        sizeList.clear();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject sort = jsonArray.getJSONObject(i);
                            sortList.add(new ClassifyBean(sort.getString("productCategoryId"), sort.getString("name"), sort.getString("sorter")));
                            sizeList.add(sort.getJSONArray("products").size() + "");
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showInfo();
                                mGoodsSortAdapter.notifyDataSetChanged();
                            }
                        });
                    } else {

                    }
                }

                Log.e(TAG, "商品信息联网成功" + jsonData);
            }
        });
    }

    private void toast(final String string) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(GoodsSortWriteActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().deleteActivity(this);
    }
}
